<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 style="text-align: center; margin-bottom: 30px;">系统修改密码</h2>

      <el-form :model="form" @submit.prevent="handleUpdatePwd">
        <!-- 用户名 -->
        <el-form-item>
          <el-input
              v-model="form.yhm"
              placeholder="用户名"
              prefix-icon="User"
              size="large"
          />
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item>
          <el-input
              v-model="form.email"
              placeholder="请输入QQ邮箱"
              prefix-icon="Message"
              size="large"
          />
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item>
          <div class="code-input-container">
            <el-input
                v-model="form.code"
                placeholder="请输入验证码"
                prefix-icon="Key"
                size="large"
                style="flex: 1; margin-right: 10px;"
            />
            <el-button
                type="primary"
                :disabled="isCountingDown"
                @click="sendCode"
                style="width: 120px;"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>

        <!-- 新密码 -->
        <el-form-item>
          <el-input
              v-model="form.newPwd"
              placeholder="输入新密码"
              prefix-icon="Lock"
              type="password"
              show-password
              size="large"
          />
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item>
          <el-input
              v-model="form.confirmPwd"
              placeholder="确认新密码"
              prefix-icon="Lock"
              type="password"
              show-password
              size="large"
          />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item style="margin-top: 30px;">
          <el-button
              type="primary"
              native-type="submit"
              style="width: 100%; height: 50px; font-size: 16px;"
              :loading="isLoading"
          >
            修改密码
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import axios from "axios";
import { useRouter } from 'vue-router'

const router = useRouter()

// 表单数据
const form = ref({
  yhm: '',       // 用户名
  email: '',     // 邮箱
  code: '',      // 验证码
  newPwd: '',    // 新密码
  confirmPwd: '' // 确认密码
})

// 状态管理
const isCountingDown = ref(false)
const countdown = ref(0)
const isLoading = ref(false)
const verifyCode = ref('') // 存储生成的验证码

// 发送验证码
const sendCode = async () => {
  // 简单验证
  if (!form.value.yhm) return ElMessage.warning('请输入用户名')
  if (!/^[1-9]\d{4,10}@qq\.com$/.test(form.value.email)) {
    return ElMessage.warning('请输入正确的QQ邮箱')
  }

  try {
    // 检查用户是否存在
    const userData = await axios.get(`/api/user/getUserByUserName/${form.value.yhm}`)
    if (!userData.data) return ElMessage.error('用户名不存在')
    if (userData.data.email !== form.value.email) {
      return ElMessage.error('邮箱与用户名不匹配')
    }

    // 生成验证码
    const code = Math.floor(1000 + Math.random() * 9000).toString()
    verifyCode.value = code

    // 发送邮件
    const loading = ElLoading.service({ text: '发送中...' })
    await axios.get(`/api/user/sendEmail/${form.value.email}/验证码/您的验证码是：${code}`)
    loading.close()

    ElMessage.success('验证码已发送到邮箱')

    // 开始倒计时
    startCountdown()
  } catch (error) {
    ElMessage.error('发送失败，请重试')
  }
}

// 倒计时
const startCountdown = () => {
  countdown.value = 60
  isCountingDown.value = true
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      isCountingDown.value = false
    }
  }, 1000)
}

// 提交修改
const handleUpdatePwd = async () => {
  // 表单验证
  if (!form.value.yhm) return ElMessage.warning('请输入用户名')
  if (!form.value.email) return ElMessage.warning('请输入邮箱')
  if (!form.value.code) return ElMessage.warning('请输入验证码')
  if (form.value.code !== verifyCode.value) return ElMessage.error('验证码错误')
  if (form.value.newPwd.length < 6) return ElMessage.warning('密码长度不能少于6位')
  if (form.value.newPwd !== form.value.confirmPwd) return ElMessage.error('两次密码不一致')

  try {
    isLoading.value = true
    // 提交修改
    const res = await axios.put('/api/user', {
      userName: form.value.yhm,
      pwd: form.value.newPwd
    })

    if (res.data) {
      ElMessage.success('密码修改成功')
      setTimeout(() => router.push('/yycsh/'), 1500)
    } else {
      ElMessage.error('修改失败')
    }
  } catch (error) {
    ElMessage.error('操作失败，请重试')
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  position: fixed;
  right: 20px;
  align-items: center;
  min-height: 100vh;
  width: 500px;
}

.login-card {
  width: 100%;
  max-width: 400px;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.code-input-container {
  display: flex;
  align-items: center;
}

.el-input {
  height: 50px;
  font-size: 16px;
}
</style>